package com.leo.server;

import com.alibaba.fastjson.JSON;
import com.leo.model.Message;
import com.leo.util.FXChatUtil;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName FXChatServer
 * @Description 简易聊天室服务器
 * @Author wangss
 * @date 2021.11.26 20:50
 * @Version 1.0
 */
public class FXChatServer extends WebSocketServer {

    public FXChatServer(int port) throws UnknownHostException {
        super(new InetSocketAddress(port));
    }

    /**
     * 监听客户端是否链接，链接打开时执行
     *
     * @param webSocket
     * @param clientHandshake
     */
    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        String username = webSocket.getResourceDescriptor().replace("/", "");
        System.out.println("用户 : [" + username + "] 登录服务");
        System.out.println("当前在线人数 : " + FXChatUtil.onlineCount.incrementAndGet());
        FXChatUtil.webSocketPools.put(username, webSocket);
    }

    /**
     * 监听客户端是否断开链接，链接关闭时执行
     *
     * @param webSocket
     * @param i
     * @param s
     * @param b
     */
    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {
        String username = webSocket.getResourceDescriptor().replace("/", "");
        System.out.println("用户 : [" + username + "] 登出服务");
        System.out.println("当前在线人数 : " + FXChatUtil.onlineCount.decrementAndGet());
        FXChatUtil.webSocketPools.remove(username);
    }

    /**
     * 监听客户端发送消息
     *
     * @param webSocket
     * @param msg
     */
    @Override
    public void onMessage(WebSocket webSocket, String msg) {
        if (StringUtils.isBlank(msg)) {
            System.out.println("服务的接收消息为空！！！");
        }
        try {
            Message message = JSON.parseObject(msg, Message.class);
            System.out.println("服务端接收到用户 [" + message.getFrom() + "] 的信息 : " + message.getText() + " 要发送给用户 [" + message.getTo() + "]");
            WebSocket to = FXChatUtil.webSocketPools.get(message.getTo());
            to.send(message.getText());
        } catch (Exception e) {
            System.out.println("消息格式不对，请调整");
        }
    }

    /**
     * 出错时执行
     *
     * @param webSocket
     * @param e
     */
    @Override
    public void onError(WebSocket webSocket, Exception e) {
        System.out.println("onError success");
        System.out.println("cause : " + e.getMessage());
        if (webSocket != null) {
            webSocket.close();
        }
    }

    /**
     * 项目启动完成执行
     */
    @Override
    public void onStart() {
        System.out.println("onStart success");
    }

    public static void main(String[] args) throws UnknownHostException {
        int port = 8887;
        try {
            port = Integer.parseInt(args[0]);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        FXChatServer fxChatServer = new FXChatServer(port);
        // 启动服务
        fxChatServer.start();
        System.out.println("ChatServer started on port: " + fxChatServer.getPort());
    }
}
